//
//  ZYCManageTourStatisticsListViewController.m
//  ZDSC
//
//  Created by ZDTX on 2021/7/26.
//

#import "ZYCManageTourStatisticsListViewController.h"
#import "ZYCLectureRecordStatisticsCell.h"
#import "PullDownMenuView.h"
#import "ZYCPullDownMenuViewController.h"
#import "ZYCCommonBaseModel.h"
#import "ZYCTourStatisticsModel.h"
#import "ZYCNoDataView.h"
static NSInteger pageSize = 10;
@interface ZYCManageTourStatisticsListViewController ()<UITableViewDelegate,UITableViewDataSource,PullDownMenuViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) PullDownMenuView *menuView;
@property (nonatomic, strong) NSArray *titleArr;
@property (nonatomic, strong) NSArray *viewControlls;
@property (nonatomic, strong) NSArray *testArr;
@property (nonatomic, strong) NSMutableArray *test1Arr;
@property (nonatomic, strong) NSArray *test2Arr;
@property (nonatomic, copy) NSString *scope;

@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic, copy) NSString *semesterId;
@property (nonatomic, copy) NSString *currentSemesterName;
@property (nonatomic, copy) NSString *courseType;
@property (nonatomic, copy) NSString *courseId;
@property (nonatomic, strong) ZYCNoDataView *noDataView;
@property (nonatomic, strong) UIButton *statisticsButton;
@end

@implementation ZYCManageTourStatisticsListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if (self.type == ZYCElectiveLevelTypePrimary) {
        self.title = @"小学部";
        self.scope = @"0";
    }else{
        self.title = @"中学部";
        self.scope = @"1";
    }
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.statisticsButton];;
    ZYCCommonBaseModel *model = self.testArr.firstObject;
    self.semesterId = model.nameId;
    self.currentSemesterName = model.name;
    
    [self.view addSubview:self.menuView];
    [self.view addSubview:self.tableView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealWithNot:) name:UpdateMenuTitleNote object:nil];
    [self loadNewData];
}



- (void)dealWithNot:(NSNotification *)note {
    if (![self.viewControlls containsObject:note.object]) {
        return;
    }
    NSInteger col = [self.viewControlls indexOfObject:note.object];
    NSArray *allValues = note.userInfo.allValues;
//    // 不需要设置标题,字典个数大于1，或者有数组
    if (allValues.count > 1 || [allValues.firstObject isKindOfClass:[NSArray class]]) return ;
    if (col == 0) {
        ZYCCommonBaseModel *model = allValues.firstObject;
        self.semesterId = model.nameId;
    }else if(col == 1){
        ZYCCommonBaseModel *model = allValues.firstObject;
        self.courseType = model.nameId;
    }else if(col == 2){
        ZYCCommonBaseModel *model = allValues.firstObject;
        self.courseId = model.nameId;
    }
    
    [self loadNewData];
}

- (void)loadNewData{
    self.pageNum = 1;
    NSDictionary *params = @{
        @"pageSize":@(pageSize),
        @"pageNum":@(self.pageNum),
        @"semesterId":self.semesterId ? self.semesterId : @"",
        @"scope":self.scope,
        @"courseType":self.courseType ? self.courseType : @"",
        @"courseId":self.courseId ? self.courseId : @"",
    };
    
    [MrjSVProgressHUD showWithStatus:@"加载中..."];
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_TourStatistics requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            [MrjSVProgressHUD dismiss];
            if (SUCCESS(responseObject[@"code"])) {
                [self.dataSource removeAllObjects];
                NSArray *array = [NSArray yy_modelArrayWithClass:[ZYCTourStatisticsModel class] json:responseObject[@"body"][@"list"]];
                if (array.count > 0) {
                    ZYCTourStatisticsModel *first = array.firstObject;
                    [self.statisticsButton setTitle:[NSString stringWithFormat:@"总计: %@次",first.allCount] forState:UIControlStateNormal];
                }
    
                [self.statisticsButton sizeToFit];
                [self.dataSource removeAllObjects];
                [self.dataSource addObjectsFromArray:array];
                [self.tableView reloadData];
                //  每次下拉刷新需要重置一下
                [self reset];
                [self.tableView.mj_header endRefreshing];
                if (self.dataSource.count == 0) {
                    self.noDataView.hidden = NO;
                    self.tableView.hidden = YES;
                }else{
                    self.noDataView.hidden = YES;
                    self.tableView.hidden = NO;
                }
            }else{
                [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
            }
        } failure:^(NSError * _Nonnull error) {
            [self.tableView.mj_header endRefreshing];
        }];
}

-(void)loadMoreData{
   self.pageNum ++;
    NSDictionary *params = @{
        @"pageSize":@(pageSize),
        @"pageNum":@(self.pageNum),
        @"semesterId":self.semesterId ? self.semesterId : @"",
        @"scope":self.scope,
        @"courseType":self.courseType ? self.courseType : @"",
        @"courseId":self.courseId ? self.courseId : @"",
    };
    [MrjSVProgressHUD showWithStatus:@"加载中..."];
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_TourStatistics requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            [MrjSVProgressHUD dismiss];
            if (SUCCESS(responseObject[@"code"])) {
                NSArray *array = [NSArray yy_modelArrayWithClass:[ZYCTourStatisticsModel class] json:responseObject[@"body"][@"list"]];
                if (array.count == 0) {
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                }else{
                    [self.dataSource addObjectsFromArray:array];
                    [self.tableView reloadData];
                    [self.tableView.mj_footer endRefreshing];
                }
            }else{
                [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
            }
        } failure:^(NSError * _Nonnull error) {
            [self.tableView.mj_footer endRefreshing];
        }];
}

- (void)reset{
    [self.tableView.mj_footer setRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [self.tableView.mj_footer resetNoMoreData];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSource.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZYCLectureRecordStatisticsCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZYCLectureRecordStatisticsCell class]) forIndexPath:indexPath];
    [cell setSectionCircularTableView:tableView withIndexPath:indexPath];
    cell.model = self.dataSource[indexPath.section];
    return cell;
}

-(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 5;
}

-(CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 280.0f;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}


#pragma mark - PullDownMenuViewDataSource
// 返回下拉菜单每列按钮标题
- (NSString *)pullDownMenu:(PullDownMenuView *)pullDownMenu titleForColAtIndex:(NSInteger)index {
    return [self.titleArr objectAtIndex:index];
}

// 返回下拉菜单每列对应的控制器
- (UIViewController *)pullDownMenu:(PullDownMenuView *)pullDownMenu viewControllerForColAtIndex:(NSInteger)index {
    ZYCPullDownMenuViewController *v = [self.viewControlls objectAtIndex:index];
    if (index == 0) {
        v.array = self.testArr.mutableCopy;

    }else if(index == 1){
        v.array = self.test1Arr.mutableCopy;
        return v;
    }else{
        v.array = self.test2Arr.mutableCopy;

    }
    return v;
}

- (NSArray *)viewControlls {
    if (!_viewControlls) {
        _viewControlls = @[[NSClassFromString(@"ZYCPullDownMenuViewController") new],[NSClassFromString(@"ZYCPullDownMenuViewController") new],[NSClassFromString(@"ZYCPullDownMenuViewController") new]];
    }
    return _viewControlls;
}


// 返回下拉菜单多少列
- (NSInteger)numberOfColsInMenu:(PullDownMenuView *)pullDownMenu {
    return self.viewControlls.count;
}
- (CGFloat)pullDownMenu:(PullDownMenuView *)pullDownMenu heightForColAtIndex:(NSInteger)index {
    if (index == 0) {
        return self.testArr.count * 44;
    }else if(index == 1){
        return self.test1Arr.count * 44;
    }else{
        return self.test2Arr.count * 44;
    }
}


- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.menuView.frame), kScreenWidth, kScreenHeight - CGRectGetMaxY(self.menuView.frame)) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[ZYCLectureRecordStatisticsCell class] forCellReuseIdentifier:NSStringFromClass([ZYCLectureRecordStatisticsCell class])];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    }
    return _tableView;
}

- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataSource;
}

- (PullDownMenuView *)menuView {
    if (!_menuView) {
        _menuView = [[PullDownMenuView alloc] initWithFrame:CGRectMake(0, kNavBarAndStatusBarHeight, kScreenWidth, 46.0f)];
        _menuView.dataSource = self;
        _menuView.separateLineColor = [UIColor clearColor];
        _menuView.titleFont = kCustomFont(@"PingFangSC-Regular", 15.0f);
    }
    return _menuView;
}


- (ZYCNoDataView *)noDataView {
    if (!_noDataView) {
        _noDataView = [[ZYCNoDataView alloc] initWithFrame:self.tableView.frame];
        _noDataView.hidden = YES;
        [self.view addSubview:_noDataView];
    }
    return _noDataView;
}
- (NSArray *)titleArr {
    if (!_titleArr) {
        _titleArr = @[self.currentSemesterName,@"课程类型",@"所属课程"];
    }
    return _titleArr;
}


- (NSMutableArray *)test1Arr {
    if (!_test1Arr) {
        _test1Arr = [NSMutableArray array];
        {
            ZYCCommonBaseModel *model = [ZYCCommonBaseModel new];
            model.name = @"兴趣课";
            model.nameId = @"1";
            [_test1Arr addObject:model];
        }
        {
            ZYCCommonBaseModel *model = [ZYCCommonBaseModel new];
            model.name = @"社团课";
            model.nameId = @"2";
            [_test1Arr addObject:model];
        }
        {
            ZYCCommonBaseModel *model = [ZYCCommonBaseModel new];
            model.name = @"基础课";
            model.nameId = @"3";
            [_test1Arr addObject:model];
        }
    }
    return _test1Arr;
}

- (NSArray *)testArr {
    if (!_testArr) {
        NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *path = [documentPath stringByAppendingPathComponent:@"semester.data"];;
        NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
        _testArr = array;
    }
    return _testArr;
}

- (NSArray *)test2Arr {
    if (!_test2Arr) {
        NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *path = [documentPath stringByAppendingPathComponent:@"course.data"];;
        NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
        _test2Arr = array;
    }
    return _test2Arr;
}


- (UIButton *)statisticsButton {
    if (!_statisticsButton) {
        _statisticsButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_statisticsButton setTitle:@"总计:0次" forState:UIControlStateNormal];
        _statisticsButton.titleLabel.font = kCustomFont(@"PingFangSC-Regular", 15.0f);

    }
    return _statisticsButton;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
